﻿<%@ WebHandler Language="C#" Class="getRandomImage" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;



public class getRandomImage : IHttpHandler, IRequiresSessionState
{

        
    
    Random rn = new Random((int)DateTime.Now.ToFileTime());
    
    public void ProcessRequest (HttpContext context) {
        int num = 7;
        string id = System.Guid.NewGuid().ToString() + "_randImage";

        int fontSize = 20;
        
        
        
        
        try
        {

            num = int.Parse(context.Request["num"]);
        }
        catch
        {
        }


        try
        {
            id = context.Request["id"] + "_randImage";

        }
        catch
        {
        }


        try
        {
            fontSize = int.Parse(context.Request["font"]);

        }
        catch
        {
        }

        
        
        context.Session[id] = getString(num);



        Bitmap bmNew = new Bitmap(120, 50);

        Graphics grNew = Graphics.FromImage((Image)bmNew);


        Brush brBack = new TextureBrush(Image.FromFile(context.Server.MapPath("randomImages/back.jpg")));
        Brush brFore = new TextureBrush(Image.FromFile(context.Server.MapPath("randomImages/fore.jpg")));

        grNew.FillRectangle(brBack, new Rectangle(0, 0, 120, 50));

        grNew.DrawString(context.Session[id].ToString(), new Font(new FontFamily("Tahoma"), fontSize),brFore,new PointF(0,0));
        


        grNew.Dispose();


        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmNew.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);

        context.Response.ContentType = "image/jpeg";
        
        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + "rand.jpg");

        context.Response.BinaryWrite(ms.ToArray());
        
        
    }


    public string getString(int nNumber)
    {
        string strNew = "";
        for (int i = 0; i < nNumber; i++)
        {
            strNew += getChar();
            
        }

        return strNew;
        
    }


    public char getChar()
    {
        

        int n = rn.Next(62);

        if (n >= 0 && n <= 9)
        {
            n = n + 48;
        }
        else if (n >= 10 && n <= 35)
        {
            n = n + 55;
        }
        else if (n >= 36 && n <= 61)
        {
            n = n + 61;
        }   
        
        
        return (char)n;
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}